/**
 * 航线新增、修改、删除开发样例. 
 * Copyright 2000-2020 ALPHA LAB.Inc
 * author:allen
 * date:2018-03-10
 */
define(["jquery","moonlight.service","moonlight.component.loading","toastr","datetimepicker","qzz.grid",
	"bootstrap","layer"], function($,moonlight,PageLoading,$toastr){

	/**
	 * 1.定义页面控制器类及其属性
	 */
	var AirlineEditController = function(){   
		//定义全局变量
		this.editGrid = null; 
		//定义常量 
		this.CONST = {
			//航线查询服务
			airlineQueryContext:"com.alphalab.moonlight.demo.service.context.IAirlineQueryContext",
			//航线增删改服务
			airlineContext:"com.alphalab.moonlight.demo.service.context.IAirlineContext",
			//航班查询服务
			airlineFlightQueryContext: "com.alphalab.moonlight.demo.service.context.IAirlineFlightQueryContext",
			//加载层
			pageLoading: new PageLoading()
		}  		 
	}
	
	/**
	 * 2.定义方法
	 */ 
	AirlineEditController.prototype = { 
	    /**
		 * 初始化方法
		 */
		init: function() { 
			this.initPage();
			this.bindEvent();	
		},
		/**
		 * 初始化页面
		 */
		initPage: function() { 
			this.initGrid();
		},
		/**
		 * 绑定事件
		 */
		bindEvent: function() {
			//查询按钮的事件响应
			$("#queryBtn6").click($.proxy(this.queryEditGrid, this));
			//重置宽高的事件响应
			$(window).resize($.proxy(this.resize, this));		
			//新增按钮的事件响应
			$("#addBtn").click($.proxy(this.showAddDialog, this));
			//保存、删除、更新按钮的事件响应
			$("#saveBtn").click($.proxy(this.saveRecord, this)); 
			$("#updateBtn").click($.proxy(this.updateRecord, this));
			$("#deleteBtn").click($.proxy(this.deleteRecord, this)); 
			//提示框的事件处理
			$("#confirm").click($.proxy(this.confirmEvent, this));
		},
		/**
		 * 获取表格格式
		 */
		getGridStructur: function(){
			var gridStructur = { 
				"height":450,
				"width":$(".grid-table").width(),
				//设置多选
				"multiselect":true,
				"suitToFit":true,
				"colNames":["航线ID","航班","出发点","终点","出发时间","到达时间","票价"], 
				"colModels":[   
					{"name":"airlineId","hidden":true},        
					{"name":"flightId"}, 
					{"name":"departure"},
					{"name":"destination"},
					{"name":"beginDate","dataType":"date","showTime":true},
					{"name":"endDate","dataType":"date","showTime":true},
					{"name":"price","scale":2,"sum":true, "dataType":"number"}
				]      
			};
			return gridStructur;
		},		
		/**
		 * 初始化编辑表格
		 */
		initGrid: function(){
			var gridStructur = this.getGridStructur();
			this.editGrid = $("#editGrid").qzzgrid(gridStructur); 
		    //绑定编辑事件
			this.editGrid.bind('onCanEditing',function(grd, fieldName, canEdit) {
	            //设置只有票价可以更新
	            if(fieldName != 'price') {
	            	return false;
	            } 
	            return canEdit;
	        });					
		},
		/**
		 * 初始化选择器
		 */
		renderSeletor: function(){
			//初始化航班下拉
			var result = moonlight.RemoteService.doPost(this.CONST.airlineFlightQueryContext, 
					"findListWithCondition",[[],"flightId",true]);
			if (result && result.success === true) {
				var flights = result.list;
				var optionDiv = "";
				$.each(flights, function(index,item){ 
					optionDiv += "<option value='"+item.flightId+"'>"+item.flightCompName+item.flightId+
						"</option>";
				}); 
				$("#flight").empty().append($(optionDiv));
				//初始化日期控件
				$(".datetimepicker").datetimepicker({"autoclose":true});
				$("#price").val("");
			} else {
				//弹窗显示错误信息
				this.showErrorDialog(result);
			}
		},
		/**
		 * 展示新增记录的弹出层
		 */
		showAddDialog: function(){ 
			this.renderSeletor(); 
			$('#itemModal').modal('show'); 
		},
		/**
		 * 查询编辑表格
		 */		
		queryEditGrid: function(){
			this.CONST.pageLoading.show(); 
			var result = moonlight.RemoteService.doPost(this.CONST.airlineQueryContext, 
					"findListWithCondition", [[],"airlineId",true]);
			if (result && result.success === true) {
				this.editGrid.value(result.list);
				this.editGrid.setFocus(); 
				this.editGrid.first(); 	
			} else {
				//弹窗显示错误信息
				this.showErrorDialog(result);
			}
			this.CONST.pageLoading.hide(); 	 			
		},
		/**
		 * 保存新增信息
		 */
		saveRecord: function(){
			//校验输入
			if (!this.validateInput()) {
				return;
			}			
			var item = {};
			item.jcls = "com.alphalab.moonlight.demo.service.model.AirlineVO";
			item.airlineId = Math.uuid();
			item.flightId = $("#flight").val();
			item.price = $("#price").val();
			item.departure = $("#departure").val();
			item.destination = $("#destination").val();
			item.beginDate = Date.parse($("#beginDate").data("datetimepicker").getDate());
			item.endDate = Date.parse($("#endDate").data("datetimepicker").getDate());   
			var result = moonlight.RemoteService.doPost(this.CONST.airlineContext, "save", [item]);
			if (result && result.success === true) {
				$toastr.success("新增成功。");
				$('#itemModal').modal('hide'); 				
			} else {
				//弹窗显示错误信息
				this.showErrorDialog(result);
			}
		},
		/**
		 * 删除选中的记录
		 */
		deleteRecord: function(){
			//获取选中的行记录
			var seletedItems = this.editGrid.getSelectedRowData();  
			if(seletedItems == null || seletedItems.length == 0){
				$toastr.info("无选中记录。");
				return;
			} 
			//是否确定删除
			$('#operateTips').modal('show'); 
			this.clearModalShadowToSingle(); 
		},
		/**
		 * 执行删除
		 */
		executeDelete: function(){
			//获取选中的行记录
			var seletedItems = this.editGrid.getSelectedRowData();  
			var isValid = true;
			//为集合中全部成员添加jcls属性
			$.each(seletedItems,function(index,item){
				if(item.airlineId.length !=32 ){
					$toastr.error("请勿删除系统内置数据，请到'新增单条记录'页签新增记录后操作。");
					isValid = false;
					return false;
				}
				item.jcls = "com.alphalab.moonlight.demo.service.model.AirlineVO";
			}); 	
			if(!isValid){
				return;
			}			
			var result = moonlight.RemoteService.doPost(this.CONST.airlineContext, "deleteList", 
					[seletedItems]);
			if (result && result.success === true) {
				$toastr.success("删除成功。");
				this.queryEditGrid();			
			} else {
				//弹窗显示错误信息
				this.showErrorDialog(result);
			}	
		},
		/**
		 * 更新记录
		 */
		updateRecord: function(){
			//获取变化的行记录
			var changedItems = this.editGrid.getChangeSet();
			if(changedItems.length == 0){
				$toastr.info("无变更记录需要更新。");
				return;
			}
			//为集合中全部成员添加jcls属性
			$.each(changedItems,function(index,item){
				item.jcls = "com.alphalab.moonlight.demo.service.model.AirlineVO";
				//删除多余属性_oldValue
				delete item._oldValue;
			}); 
			var result = moonlight.RemoteService.doPost(this.CONST.airlineContext, "updateList", 
					[changedItems]); 
			if (result && result.success === true) {
				$toastr.success("更新成功。");			
			} else {
				//弹窗显示错误信息
				this.showErrorDialog(result);
			}		
		},	
		/**
		 * 校验输入
		 */
		validateInput: function(){
			if ($("#price").val().length == 0) {
				$toastr.warning("票价不能为空。");
				return false;
			} 
			if (isNaN($("#price").val())){
				$toastr.warning("票价请输入数字。");
				return false;				
			}
			if ($("#beginDate").val().length == 0){
				$toastr.warning("出发时间不能为空。");
				return false;	
			}
			if ($("#endDate").val().length == 0){
				$toastr.warning("到达时间不能为空。");
				return false;	
			}			
			var startDate = $("#beginDate").data("datetimepicker").getDate();
			var endDate = $("#endDate").data("datetimepicker").getDate(); 
			if(startDate > endDate){
				$toastr.warning("出发时间不能大于到达时间。");
				return false;
			}	
			if($("#departure").val() == $("#destination").val()){
				$toastr.warning("出发点不能等于终点。");
				return false;
			}			
			return true;
		}, 
		/**
		 * 设置弹出层的遮罩只有一个，避免背景太黑
		 */
		clearModalShadowToSingle: function(){
	    	//去掉多余的遮罩   
	    	$(".modal-backdrop").nextAll(".modal-backdrop").removeClass("modal-backdrop");			
		},
		/**
		 * 提示框确认事件响应
		 */
		confirmEvent: function(){
			$('#operateTips').modal('hide'); 
			this.executeDelete();
		},
		/**
		 * 重置宽高
		 */
		resize: function(){
			//对已初始化的表格重置宽高
			this.editGrid.setWidth($(".grid-table").width());
		},
		/**
		 * 异常信息展示
		 */
		showErrorDialog: function(errorObj) {
			if (!errorObj) {
				layer.open({
				    title: '提示',
				    content: '服务器连接失败'
				});
				return;
			}			
			if (!(errorObj.code || errorObj.msg)) {
				layer.open({
				    title: '提示',
				    content: '服务器返回数据类型错误'
				});
				return;
			}
			var layOptions = {
				title: '提示',
				area: '400px',
				content: '错误码：' + errorObj.code + '<br>错误信息：' + errorObj.msg					
			};
			var errStr = errorObj.errorDetail;
			if (errStr && errStr.length > 0) {
				var exceptionStr = errStr.replace(/\n/g,'<br>&emsp;&emsp;');
				layOptions.btn = ['查看详情', '关闭'];
				layOptions.yes = function(index, layero){
				    layer.open({
					    title: '错误详情',
					    area: '920px',
					    content: exceptionStr
				    });
				};
			}
			layer.open(layOptions);			
		}		
	}
	
	/**
	 * 3.创建对象
	 */
	var airlineEditController = new AirlineEditController();
	
	/**
	 * 4.返回对象
	 */
	return airlineEditController; 		
		
});
